import axios from "axios";
import Qs from "qs";
import {
  BAIDU,
  operationOut
} from "./api";
import {
  Error
} from "./notification"; //引入Notification通知组件
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import {
  Loading
} from "element-ui";
let loading;
let loadingCount = 0;

function start() {
  loading = Loading.service({
    lock: true,
    text: "加载中",
    background: "rgba(0,0,0,0.7)"
  });
}

function end() {
  loading.close();
}

function showLoaing() {
  if (loadingCount == 0) {
    start();
  }
  loadingCount++;
}

function hideLoading() {
  loadingCount--;
  if (loadingCount == 0) {
    end();
  }
}
//加载条配置
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
});
axios.defaults.timeout = 300000; //请求超时时间
axios.defaults.withCredentials = true; //配置允许跨域携带cookie
axios.defaults.dataType = "JSON"; //data类型
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded"; //设置post默认请求头
// axios.defaults.baseURL = "";//配置axios的默认URL,如果只是单个域名的话可以手动切换开发环境和生产环境
// 请求时的拦截
axios.interceptors.request.use(
  config => {
    // 发送请求之前做一些处理
    //设置公共的自定义请求头
    let userInfo = sessionStorage.getItem("userInfo");
    if (userInfo && userInfo !== null && userInfo !== "" && userInfo !== "{}") {
      userInfo = JSON.parse(userInfo);

      config.headers.token = escape(userInfo.token); //例如token
      config.headers.companyId = window.sessionStorage.getItem("companyId") == null ? userInfo.companyId : window.sessionStorage.getItem("companyId"); //例如token
      config.headers.indexs = 2; //例如token


      NProgress.start(); //开始加载进度条
      showLoaing();
    }

    return config;
  },
  error => {
    // 当请求异常时做一些处理
    Error("网络似乎开小差,请稍后再试!");
    return Promise.reject(error);
  }
);
/**
 *响应时拦截 返回响应时做一些处理
 */
axios.interceptors.response.use(
  response => {
    let data;
    if (response.data === undefined) {
      // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
      data = response.request.responseText;
    } else {
      data = response.data;
      const url = response.config.url;
      const Index = url.lastIndexOf("/api");
      const str = url.substring(Index, url.length);
      if (data.code == 300) {
        window.location = "#/Login";
        window.sessionStorage.clear();
      }
      // console.log(str)
      if (data.code !== 200) {
        if (
          str === "/api/v1.Operation/operationOut" ||
          str === "/api/v1.Mydevice/deviceOut" ||
          str === "/api/v1.Device/deviceQrcode"

        ) {
          // Error(data.msg);
        } else {
          if (str === "/api/v1.Login/loginOut") {
            // console.log(data.msg)

          } else {}
          Error(data.msg);

        }
      }
    }
    NProgress.done(); // 结束进度条
    hideLoading();
    return data;
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;

        case 401:
          error.message = "未授权，请登录";
          break;

        case 403:
          error.message = "拒绝访问";
          break;

        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;

        case 408:
          error.message = "请求超时";
          break;

        case 500:
          error.message = "服务器内部错误";
          break;

        case 501:
          error.message = "服务未实现";
          break;

        case 502:
          error.message = "网关错误";
          break;

        case 503:
          error.message = "服务不可用";
          break;

        case 504:
          error.message = "网关超时";
          break;

        case 505:
          error.message = "HTTP版本不受支持";
          break;

        default:
          error.message = error.response.message;
      }
    }
    Error(error.message);
    NProgress.done(); // 结束进度条
    return Promise.reject(error);
  }
);

let root = ""; //生产环境域名

/**
 * get方法，对应get请求,
 * path 接口地址,
 * params 请求的参数,
 * type 当代理多域名时,判断该使用哪个域名,
 * headers 携带的请求头
 */
export function getRequest(path, params, type, headers) {
  if (!type) {
    root = process.env.MAIN_ENV;
  } else if (type === BAIDU) {
    root = process.env.BAI_DU;
  } else {
    root = process.env.MAIN_ENV;
  }
  if (!params) {
    params = {};
  }
  if (!headers) {
    headers = {};
  }
  const url = root + path;
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
        headers
      })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * post方法，对应post请求,
 * path 接口地址,
 * params 请求的参数,
 * type 当代理多域名时,判断该使用哪个域名,
 * headers 携带的请求头
 */
export function postRequest(path, params, type, headers) {
  if (!type) {
    root = process.env.MAIN_ENV;
  } else if (type === BAIDU) {
    root = process.env.BAI_DU;
  } else if (type === "kefu") {
    root = process.env.kefu;
  } else {
    root = process.env.MAIN_ENV;
  }
  if (!params) {
    params = {};
  }
  if (!headers) {
    headers = {};
  }
  const url = root + path;
  return new Promise((resolve, reject) => {
    axios
      .post(url, Qs.stringify(params), {
        headers
      })

      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
